package com.gexin.common.log;

import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;
import org.apache.log4j.helpers.PatternParser;
import org.apache.log4j.helpers.PatternConverter;
import com.gexin.common.log.GeXinLogKit.LogType;
import com.gexin.common.utils.StringUtil;

public class GeXinLogLayout extends Layout {

	public final static String DEFAULT_CONVERSION_PATTERN = "%m%n";

	public final static String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n";

	protected final int BUF_SIZE = 256;
	protected final int MAX_CAPACITY = 1024;

	// output buffer appended to when format() is invoked
	private StringBuffer sbuf = new StringBuffer(BUF_SIZE);

	private String pattern;

	private PatternConverter head;

	/**
	   Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN.

	   The default pattern just produces the application supplied message.
	*/
	public GeXinLogLayout() {
		this(DEFAULT_CONVERSION_PATTERN);
	}

	/**
	   Constructs a PatternLayout using the supplied conversion pattern.
	*/
	public GeXinLogLayout(String pattern) {
		this.pattern = pattern;
		head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).parse();
	}

	public void setConversionPattern(String conversionPattern) {
		pattern = conversionPattern;
		head = createPatternParser(conversionPattern).parse();
	}

	public String getConversionPattern() {
		return pattern;
	}

	public void activateOptions() {
		// nothing to do.
	}
	public boolean ignoresThrowable() {
		return true;
	}

	protected PatternParser createPatternParser(String pattern) {
		return new PatternParser(pattern);
	}
	
	public String format(LoggingEvent event) {
		if (sbuf.capacity() > MAX_CAPACITY) {
			sbuf = new StringBuffer(BUF_SIZE);
		} else {
			sbuf.setLength(0);
		}

		PatternConverter c = head;

		while (c != null) {
			c.format(sbuf, event);
			c = c.next;
		}
		
		if(event.getLevel()==Level.ERROR){
			StringBuffer data=new StringBuffer();
			String msg =  event.getRenderedMessage();
			ThrowableInformation  info  =  event.getThrowableInformation();
			if(info!=null){
				msg=msg+ "异常信息: " +info.getThrowable().getMessage();
				data.append(StringUtil.array2String(info.getThrowableStrRep(), "<br>"));
			}else{
				data.append("类:" + event.getLocationInformation().getClassName() + "<br>");
				data.append("方法：" + event.getLocationInformation().getMethodName() + "<br>");
				data.append("位置：" + event.getLocationInformation().getLineNumber() + "行");
			}
			GeXinLogKit.postLog(LogType.Error, msg, data.toString());
		}
		return sbuf.toString();
	}
}
